package com.hs.mpdemo_01.service.impl;

import com.hs.mpdemo_01.service.FileUploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName FileUploadServiceImpl
 * @Description  文件上传的service
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Override
    public String uploadOneFile(MultipartFile multipartFile, HttpSession session) throws IOException {
        // 获取上传的文件的文件名
        String fileName = multipartFile.getOriginalFilename();
        // 处理文件重名问题: 截取文件扩展名，用UUID替代文件名
        String hzName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID().toString() + hzName;
        // 获取服务器中upload目录的路径
        ServletContext servletContext = session.getServletContext();
        String rootPath = servletContext.getRealPath("upload"); // 获取upload文件夹的真实路径
        // 当前日期文件夹
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateDirPath = sdf.format(new Date());
        File file = new File(rootPath+ File.separator + dateDirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        // 文件上传的最终路径
        String finalPath = rootPath + File.separator + dateDirPath + File.separator
                + fileName;
        String projectPath = "upload/" + dateDirPath + "/"+fileName;
        System.out.println("文件上传的最终路径:" + finalPath);
        //实现上传功能
        multipartFile.transferTo(new File(finalPath));
        return projectPath;
    }
}
